<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传用户" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入上传用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" prop="createTimes">
        <el-date-picker
          v-model="queryParams.createTimes"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="分类标签" prop="type">
        <el-select v-model="queryParams.type" placeholder="分类标签" clearable>
          <el-option
            v-for="dict in dict.type.article_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="渠道" prop="channelCode">
        <el-select v-model="queryParams.channelCode" placeholder="请选择渠道">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in channelList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="机构" prop="strategyOrgan">
        <el-cascader
          style="width:100%"
          clearable
          @change="strategyOrganChange(strategyOrgan)"
          :options="organizationList"
          :props="organizationList_props"
          v-model="strategyOrgan"
          :show-all-levels="false"
          placeholder="请选择组织机构"
        ></el-cascader>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleStateMultiple('publish')"
        >全部上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleStateMultiple('remove')"
        >全部下架</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table v-loading="loading" :data="essayList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="articleId" width="100" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="渠道" align="center" prop="channelName" width="100"></el-table-column>
      <el-table-column label="机构" align="center" prop="organName" width="100"></el-table-column>
      <!-- <el-table-column label="字数" align="center" prop="createBy" width="100" /> -->
      <el-table-column label="上传者" align="center" prop="createBy" width="100" />
      <el-table-column label="上传时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设置分类" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.article_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <template v-for="(item,index) in dict.type.article_status">
            <span :key="index" v-if="item.value == scope.row.status">{{item.label}}</span>
          </template>
          <!-- {{dict.type.article_status}} -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width:60px;"
            @click="handleUpdate(scope.row,'preview')"
          >预览</el-button>
          <!-- <el-button
            size="mini"
            type="info"
            style="width:60px;"
            @click="handleUpdate(scope.row,'detail')"
            v-hasPermi="['essay:essayQuery:detail']"
          >详情</el-button>-->
          <el-button
            size="mini"
            type="danger"
            style="width:60px;"
            v-if="scope.row.status == '4'"
            @click="handleState(scope.row,'Remove')"
          >下架</el-button>
          <el-button
            size="mini"
            type="success"
            style="width:60px;"
            v-else
            @click="handleState(scope.row,'publish')"
          >上架</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="ql-container ql-snow" v-if="title =='预览'">
          <div class="ql-editor">
            <div v-html="form.content"></div>
          </div>
        </div>
        <el-row v-if="title !='预览'">
          <el-col :span="12">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章分类" prop="type">
              <el-select v-model="form.type" placeholder="请选择文章分类">
                <el-option
                  v-for="dict in dict.type.article_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道" prop="channelCode">
              <el-select v-model="form.channelCode" placeholder="请选择渠道">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in channelList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构" prop="strategyOrgan">
              <el-cascader
                clearable
                @change="strategyOrganChange2"
                ref="casTree"
                :options="organizationList"
                :props="organizationList_props"
                v-model="strategyOrgan2"
                :show-all-levels="false"
                placeholder="请选择组织机构"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文章封面">
              <el-upload
                :action="uploadUrl"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-success="handleAvatarSuccess"
                :on-remove="handleRemove"
                :file-list="fileList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文章简介" prop="introduction">
              <el-input type="textarea" :rows="4" placeholder="请输入文章简介" v-model="form.introduction"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文章内容" prop="content">
              <editor v-model="form.content" :min-height="300" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title !='预览'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findList,
  findById,
  delEssay,
  addEssay,
  updateEssay,
} from "@/api/system/essay";
import { formatDate } from "@/utils/index.js";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import axios from "axios";
export default {
  name: "Notice",
  dicts: ["article_type", "article_status"],
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      dialogImageUrl: "",
      dialogVisible: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      essayList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      strategyOrgan: [],
      queryParams: {
        title: "",
        createBy: "",
        type: "",
        createTimes: [],
        channelCode: "",
        organId: "",
      },
      organizationList: [],
      organizationList_props: {
        multiple: false,
        label: "organName",
        value: "organCode",
        children: "childOrganList",
        checkStrictly: true,
      },
      channelList: [],
      // 表单参数
      form: {},
      selection: [], //多选框数据
      // 表单校验
      rules: {},
      strategyOrgan2: [],
      form: {
        type: "",
        title: "",
        content: "",
        cover: "",
        introduction: "",
        channelCode: "",
        organId: "",
        organName: "",
      },
      fileList: [],
    };
  },
  created() {
    // console.log(new Date(),'new Date()new Date()')
    this.getListEnumList();
    this.getList();
  },
  methods: {
    strategyOrganChange(val) {
      if (val.length !== 0) {
        this.queryParams.organId = val[val.length - 1];
      } else {
        this.queryParams.organId = "";
      }
    },
    strategyOrganChange2(val) {
      console.log(
        val,
        this.$refs.casTree.getCheckedNodes()[0].pathLabels.toString(),
        "va11111l===="
      );
      this.form.organName = this.$refs.casTree
        .getCheckedNodes()[0]
        .pathLabels.toString();

      if (val.length !== 0) {
        this.form.organId = val[val.length - 1];
      } else {
        this.form.organId = "";
      }
    },
    async getListEnumList() {
      try {
        const response = await axios.post(
          process.env.VUE_APP_BASE_API + "/strategy/queryEnumList",
          {}
        );
        if (response.data.enumList) {
          if (response.data.enumList.channelType) {
            this.channelList = response.data.enumList.channelType;
          }
          if (response.data.enumList.organList) {
            this.organizationList = JSON.parse(
              response.data.enumList.organList
            );
          }
        }
      } catch (error) {
        console.error("Error fetching users:", error);
      }
    },
    /** 查询公告列表 */
    getList() {
      this.loading = true;
      if (
        this.queryParams.createTimes.length > 0 &&
        this.queryParams.createTimes != undefined &&
        this.queryParams.createTimes != null
      ) {
        this.queryParams.createTimeStart = this.queryParams.createTimes[0];
        this.queryParams.createTimeEnd = this.queryParams.createTimes[1];
      } else {
        this.queryParams.createTimeStart = "";
        this.queryParams.createTimeEnd = "";
      }
      findList(this.queryParams).then((response) => {
        this.essayList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.fileList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: undefined,
        noticeTitle: undefined,
        noticeType: undefined,
        noticeContent: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    // /** 搜索按钮操作 */
    handleQuery() {
      //   this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.articleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.selection = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章";
      this.strategyOrgan2 = "";
      this.fileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.reset();
      const articleId = row.articleId || this.ids;
      findById(articleId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = type == "preview" ? "预览" : "添加文章";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.articleId != undefined) {
            updateEssay(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            (this.form.createBy = "admin"),
              (this.form.cover = this.dialogImageUrl);
            //  formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
            this.form.createTime = "";
            addEssay(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.fileList = [];
            });
          }
        }
      });
    },
    /** 上架和下架 按钮操作 */
    handleState(row, type) {
      let articleIds = [];
      // const articleId = row.articleId || this.ids
      articleIds.push(row.articleId);
      let status = "";
      if (row.status == "2") {
        status = "4";
      } else {
        status = "2";
      }
      let obj = {
        articleIds: articleIds,
        status: status,
      };
      this.$modal
        .confirm(
          "是否确认" +
            (type == "publish" ? "上架" : "下架") +
            '文章标题为"' +
            row.title +
            '"的数据项？'
        )
        .then(function () {
          return delEssay(obj);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(type == "publish" ? "上架成功" : "下架成功");
        })
        .catch(() => {});
    },
    //多条上架和下架功能
    handleStateMultiple(type) {
      console.log(this.selection, "this.selection");
    },
    handleRemove(file, fileList) {
      this.dialogImageUrl = "";
      console.log(file, fileList, "-------");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      console.log(this.dialogImageUrl, "this.dialogImageUrl");
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file);
      this.dialogImageUrl = file.url;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
  },
};
</script>
